package com.zzj.seckill.rabbitmq;

import com.zzj.seckill.pojo.SeckillMessage;
import com.zzj.seckill.pojo.SeckillOrder;
import com.zzj.seckill.pojo.User;
import com.zzj.seckill.service.IGoodsService;
import com.zzj.seckill.service.IOrderService;
import com.zzj.seckill.utils.JsonUtil;
import com.zzj.seckill.vo.GoodsVo;
import com.zzj.seckill.vo.RespBean;
import com.zzj.seckill.vo.RespBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class MQReceiver {
//    @RabbitListener(queues = "queue")
//    public void receive1(Object msg){
//        log.info("接收消息："+msg);
//    }
//    @RabbitListener(queues = "queue01")
//    public void receive2(Object msg){
//        log.info("queue01接收消息："+msg);
//    }
//    @RabbitListener(queues = "queue02")
//    public void receive3(Object msg){
//        log.info("queue02接收消息："+msg);
//    }

    /**
     * 下单操作
     */
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IOrderService orderService;




    @RabbitListener(queues = "seckillQueue")
    public void receive(String message){
        log.info("接收到的消息："+message);
        SeckillMessage seckillMessage = JsonUtil.jsonStr2Object(message, SeckillMessage.class);
        Long goodId = seckillMessage.getGoodId();
        User user = seckillMessage.getUser();
        GoodsVo goods = goodsService.findGoodsVoByGoodsId(goodId);
        if(goods.getStockCount() < 1){
            return;
        }
        // 判断是否重复抢购
        SeckillOrder seckillOrder = ((SeckillOrder) redisTemplate.opsForValue().get("order:" + user.getId() + ":" + goodId));
        if( seckillOrder != null){
            return;
        }
        // 下单操作
        orderService.seckill(user,goods);

    }
}
